package com.ctshk.rpc.order.airexpress.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.OrderPaymentStatus;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.rpc.order.airexpress.entity.AirportExpressOrder;
import com.ctshk.rpc.order.airexpress.mapper.AirportExpressOrderMapper;
import com.ctshk.rpc.order.airexpress.service.IAirportExpressOrderTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * <p>
 * 机场快线订单表 服务实现类
 * </p>
 *
 * @author 叶冠峰
 * @since 2021-02-23
 */
@Slf4j
@DubboService
public class AirportExpressOrderTaskServiceImpl extends ServiceImpl<AirportExpressOrderMapper, AirportExpressOrder> implements IAirportExpressOrderTaskService {
    @Autowired
    AirportExpressOrderMapper airportExpressOrderMapper;

    @Override
    public Result notPaid(Long id) {
        AirportExpressOrder airportExpressOrder = airportExpressOrderMapper.selectOne(new QueryWrapper<AirportExpressOrder>().lambda()
                .eq(AirportExpressOrder::getId, id)
                .eq(AirportExpressOrder::getIsDeleted, IsDeletedCode.NO.getCode())
                .select(AirportExpressOrder::getId, AirportExpressOrder::getOrderNumber, AirportExpressOrder::getPaymentStatus));
        if (airportExpressOrder == null) {
            log.error("【机场快线订单定时任务-未支付超时】找不到订单, orderNumber:{}", airportExpressOrder.getOrderNumber());
            throw new BusinessException(SystemError.AIREXPRESS_ORDER_60002);
        }
        log.info("【机场快线订单定时任务-未支付超时】修改订单状态, orderNumber:{}, data:{}", airportExpressOrder.getOrderNumber(), JSON.toJSONString(airportExpressOrder));
        if (Objects.equals(airportExpressOrder.getPaymentStatus(), OrderPaymentStatus.UN_PAYMENT)) {
            airportExpressOrder.setPaymentStatus(OrderPaymentStatus.ALREADY_CANCEL.getCode());
            airportExpressOrder.setModifiedId(1L);
            airportExpressOrder.setGmtModified(LocalDateTime.now());
            airportExpressOrderMapper.update(null, new UpdateWrapper<AirportExpressOrder>().lambda()
                    .eq(AirportExpressOrder::getId, id)
                    .set(AirportExpressOrder::getPaymentStatus, OrderPaymentStatus.ALREADY_CANCEL.getCode())
                    .set(AirportExpressOrder::getModifiedId, 1L)
                    .set(AirportExpressOrder::getGmtModified, LocalDateTime.now()));
        }
        return Result.success();
    }
}
